package pri.zjy.backTracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangjy
 * @description
 * @date 2025/3/11 21:56
 */
public class Permute_4622222 {

    public static void main(String[] args) {
        Permute_4622222 permute46 = new Permute_4622222();
        int[] nums = new int[]{1, 2, 3};
        List<List<Integer>> res = permute46.permute2(nums);
        res.forEach(System.out::println);
    }


    public List<List<Integer>> permute2(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> pathList = new ArrayList<>();
        int[] used = new int[nums.length];

        backTracking2(nums, used, pathList, result);
        return result;
    }

    public List<Integer> backTracking2(int[] nums, int[] used, List<Integer> path, List<List<Integer>> res) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return path;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i] == 1) continue;
            // 记录已使用的元素
            used[i] = 1;
            path.add(nums[i]);
            // 递归
            backTracking2(nums, used, path, res);
            // 回溯
            used[i] = 0;
            path.remove(path.size() - 1);
        }
        // 每层纵向遍历完后，也要返回上一层，从而进行回溯的操作
        return path;
    }

}
